package com.smart.manager.pop.repository;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.pop.entities.body.RActivityRecord;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.pop.entities.models.PopDisRecord;
import com.smart.manager.pop.entities.models.query.QPopDisInviter;
import com.smart.manager.pop.entities.models.query.QPopDisRecord;
import com.smart.service.remind.RemindService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 注册活动-达成管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class DisRecordRepository {


    private final RemindService remindService ;
    
    public Page<PopDisRecord> pageList(RActivityRecord.SearchBody search) {
        QPopDisRecord query = new QPopDisRecord();
        Opt.ofNullable(search.getInviterId()).ifPresent(x -> query.inviter.id.eq(x));
        Opt.ofBlankAble(search.getInviterPhoneNumber()).ifPresent(x -> query.inviter.phone.contains(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<PopDisRecord>().load(query.findPagedList());
    }



    public void saveRecord(MemberProfileMain newMember, long inviterId) {
        MemberView memberView = new MemberView().setId(newMember.getId());
        PopDisInviter popDisInviter = new QPopDisInviter().id.eq(inviterId).setMaxRows(1).findOne();
        if (ObjectUtil.isNull(popDisInviter)) {
            log.warn("无法识别的分销人信息");
            return;
        }
        new PopDisRecord().setMember(memberView).setInviter(popDisInviter).setBindTime(LocalDateTime.now()).save();
        popDisInviter.setRts2( popDisInviter.getRts1()+1).update();
        remindService.sendB2cBind(newMember ,popDisInviter) ;
    }
}
